#pragma once
#include "Reactor.hpp"
#include "Socket.hpp"
#include <memory>
#include "Commn.hpp"
#include "Log.hpp"
#include "IOService.hpp"
#include "Calculator.hpp"

namespace ListenerModule
{
    using namespace LogModule;
    using namespace SocketModule;
    class Listener : public Connection
    {
    private:
        std::shared_ptr<Socket> _tsvr;
    public:
        Listener(int port) : _tsvr(std::make_shared<TcpSocket>())
        {
            _tsvr->BuildTckSocket(port);
            // 设置为非阻塞
            SetNonBlock(_tsvr->FD());
            // 添加进入connection中
            SetFd(_tsvr->FD());
        }
        void Reader() override
        {
            //谁说每次只能获取一个连接??
            while (true)
            {
                InetAddr peer;
                int aerrno = 0;
                int socketfd = _tsvr->Acceptor(&peer, &aerrno);
                if (socketfd > 0) 
                {
                    //添加连接
                    LOG(LogLevel::INFO) << "get a fd: " << socketfd << " info: " << peer.Info();
                    //添加连接😍😍
                    connction_ptr con = std::make_shared<IoService>(socketfd);
                    //添加数据处理（反序列化与序列化）的函数
                    con->RegisterHandler(HandlerRequest);
                    GetOwner()->InsertConnection(con);
                }
                else 
                {
                    if (aerrno == EAGAIN) 
                    {
                        LOG(LogLevel::INFO) << "all accpet done";
                        break;
                    }
                    else if (aerrno == EINTR){
                        LOG(LogLevel::INFO) << "被信号打断,接着accept";
                        continue;
                    }
                    else  
                    {
                        LOG(LogLevel::ERROR) << "accept error";
                        break;
                    }
                }
            }
        }
        virtual ~Listener() {}
    };
}
